import { Doctor } from '../../types/doctor'
import { Page, PageReq } from '../../types/page'
import { DoctorDao } from '../dao/doctorDao'
import { encryptPassword, decryptPassword } from '../../utils/crypto'

export class DoctorService {
  /**
   * 创建医生
   */
  static async create(doctor: Omit<Doctor, 'id'>): Promise<number | undefined> {
      const encryptedDoctor = {
        ...doctor,
        password: encryptPassword(doctor.password)
      }
      return DoctorDao.create(encryptedDoctor)
  }

  /**
   * 更新医生信息
   */
  static async update(doctor: Partial<Doctor>): Promise<void> {
    if (doctor.password) {
      doctor.password = encryptPassword(doctor.password)
    }
    return DoctorDao.update(doctor)
  }

  /**
   * 删除医生
   */
  static async delete(id: number): Promise<void> {
    if(id === 1){
      throw new Error('不能删除管理员')
    }
    return DoctorDao.delete(id)
  }

  /**
   * 获取医生详情
   */
  static async getById(id: number): Promise<Doctor | null> {
    const doctor = await DoctorDao.getById(id)
    doctor.password = ''
    return doctor
  }

  /**
   * 获取医生列表
   */
  static async list(): Promise<Doctor[]> {
    return DoctorDao.list()
  }

  /**
   * 分页查询医生列表
   */
  static async page(params: PageReq<Doctor>): Promise<Page<Doctor>> {
    return DoctorDao.page(params)
  }

  /**
   * 医生登录
   */
  static async login(account: string, password: string): Promise<Doctor | null> {
    console.log(account, password)
    const doctor = await DoctorDao.getByAccount(account)
    if (!doctor) return null
    //console.log(doctor)
    //console.log(doctor.password)
   // const dbPwd = decryptPassword(doctor.password)
    //console.log(dbPwd)
    // 实际项目中这里应该比较加密后的密码
    // 示例中前端已加密，直接比较
    if (decryptPassword(doctor.password) !== password) {

      return null
    }
    console.log('11222',doctor)
    return doctor
  }

    /**
     * 密码修改
     * 先验证旧密码是否正确，若不正确，提示：旧密码不正确，请重新输入
     * 若正确，验证两次新密码是否相同，若不同，提示：输入的两次新密码不相同，请重新输入
     * 若相同，对新密码加密后保存
     * @param id 患者ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param newPassword1 新密码
     */
    static async updatePassword(id: number, oldPassword: string, newPassword: string, newPassword1: string) : Promise<void>{
      const doctor = await DoctorDao.getById(id);
      if(!doctor){
        throw new Error('医生不存在');
      }
      if (decryptPassword(doctor.password) !== oldPassword) {
        throw new Error('旧密码不正确');
      }
      if(newPassword !== newPassword1){
        throw new Error('输入的两次新密码不相同');
      }
      newPassword = encryptPassword(newPassword)
      await DoctorDao.updatePassword(id, newPassword);
    }
}